import pandas as pd
from manim import *
from openpyxl import load_workbook

class BubbleSort(Scene):


    def read_excel(self,file_path):
        workbook = load_workbook(file_path)
        sheet = workbook.active

        # 获取行数和列数
        rows = sheet.max_row
        cols = sheet.max_column

        # 创建二维数组
        self.data = [[None] * cols for _ in range(rows)]

        # 逐行逐列读取数据并存储在二维数组中
        for r in range(1, rows + 1):
            for c in range(1, cols + 1):
                self.data[r - 1][c - 1] = sheet.cell(row=r, column=c).value
    def read_data(self):
        # Read the Excel file and select the first column
        df = pd.read_excel("C:/AMark/Code/python/GDP/data/ExcelData/4GDP-总值.xlsx")
    def construct(self):
        self.COLOR = [BLUE, GREEN, RED, PINK, ORANGE, MAROON_B, TEAL, PURPLE_B, GREY_BROWN]
        self.bubbleSort([12, 14, 4, 10])

    def init_vmobj(self, arr):
        '''
            初始化场景元素
        '''
        self.name = ["中国","法国", "印度","美国"]
        self.vmArr = []
        g = VGroup()
        for i in range(len(arr)):
            r1 = Rectangle(width=1, height=arr[i] / 2, fill_color=self.COLOR[i % len(self.COLOR)], fill_opacity=1)
            t1 = Text(self.name[i]).scale(0.5)
            rec = VGroup(r1, t1)
            self.vmArr.append(rec)
            g.add(rec)
        g.arrange(RIGHT, aligned_edge=DOWN)

        self.add(g)
        self.wait()

    def bubbleSort(self, arr):
        '''
            冒泡排序
        '''
        self.init_vmobj(arr)
        for i in range(1, len(arr)):
            for j in range(0, len(arr) - i):
                self.play(Indicate(self.vmArr[j]))
                self.play(Indicate(self.vmArr[j + 1], color=RED))
                if arr[j] > arr[j + 1]:
                    arr[j], arr[j + 1] = arr[j + 1], arr[j]
                    self.cyc_move(self.vmArr[j], self.vmArr[j + 1])
                    self.vmArr[j], self.vmArr[j + 1] = self.vmArr[j + 1], self.vmArr[j]
        return arr

    def cyc_move(self, vm1, vm2):
        '''
            交换两个元素位置
        '''
        vm1.generate_target()
        vm1.target.next_to(vm2, ORIGIN, aligned_edge=DOWN)

        vm2.generate_target()
        vm2.target.next_to(vm1, ORIGIN, aligned_edge=DOWN)

        self.play(MoveToTarget(vm1), MoveToTarget(vm2))
        self.wait()



